import React, { useRef, useContext, useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Badge, Button, message, Row, Col, Table, Form, InputNumber, Popconfirm, Drawer, Spin,Upload ,Modal} from 'antd';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import { ProductType, OrderInfo } from '../../../model';
import { DownOutlined, PlusOutlined, QuestionCircleOutlined, UploadOutlined, UpOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormText, ProFormDatePicker, ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import ProductChooseForm from '../../../components/Common/ProductChooseForm';
import { saveOrderApi, toPlaceOrderNew, myOrderData, exportOrder, orderDetailDataById, updateOrder, getList4Dealer,orderBillInfo } from '../service';
import UpDownLabel from '@/components/Common/UpDownLabel';
import { getCurrentDate, manufacturerOption, priceOption } from '../../../utils/utils';
import { exportFile, moneyFormat, moneyFormat2,accAdd,accSub,accMul,momentNow } from '@/utils/utils';

import { history } from 'umi';
import { RcFile } from 'antd/lib/upload';
import request from '@/utils/request';
import OrderHistory from '@/components/Common/OrderHistory';
const EditableContext = React.createContext(null);

const EditableRow = ({
  index,
  ...props
}) => {
  const [form] = Form.useForm();
  return <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props}/>
      </EditableContext.Provider>
    </Form>;
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<any>(null);
  const form = useContext<any>(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex]
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      if (values < record.minimum && record.is_gifts == 0) {
        message.warning('不能小于最小起订量：' + record.minimum);
        return;
      }

      toggleEdit();
      handleSave({ ...record,
        ...values
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? <Form.Item style={{
      margin: 0
    }} name={dataIndex} rules={[{
      required: true,
      message: `数量必填`
    }]} >
      <InputNumber ref={inputRef} onPressEnter={save} onBlur={save} min={0} max={record.max ? record.max : undefined} step={record.packing_unit==='把'?10:1} precision={0}/> 
      </Form.Item> : <div style={{
      padding: '4px 12px',
      paddingRight: 24,
      cursor: 'pointer',
      border: '1px solid #d9d9d9',
      borderRadius: '4px'
    }} onClick={toggleEdit}>
        {children}
      </div>;
  }

  return <td {...restProps} >{childNode}</td>;
};

class Order extends React.Component {
  formRef = React.createRef<any>();
  actionRef = React.createRef<any>();
  orderHistoryRef:any = React.createRef();
  totalMoney = 0;
  state:any = {
    activeKey: 'tab0',
    proModalVisible: false,
    detailFlag: false,
    editOrder: false,
    sentArray: [],
    gift: 0,
    detailProduct: [],
    detailRecv: {},
    detailOrder: {},
    newDataSource: [],
    giftFlag: false,
    showCreate: false,
    initData: {},
    address: {},
    saleInfo: {},
    editing: false,
    useMoney: 0,
    disMoney: 0,
    totalMoney: 0,
    spinningFlag: false,
    num0: 0,
    num1: 0,
    num2: 0,
    num3: 0,
    btnLoading: false,
    fileList: [],
    fileId: '',
    showDiscount: false,
    disList: [],
    showGift: false,
    giftList: [],
    factoryRules:[],
    payInfo:{billName:''},
    sentList:[],
    sentPrice: 0,
    dealerCode:'',
    editFlag:false,
    more:true,
    historyVisible:false
  };
  userInfo: any;

  constructor(props: any) {
    super(props);
    this.userInfo = {
      'userId': sessionStorage.getItem('userId'),
      'dealerId': sessionStorage.getItem('dealerId')
    };

    if (props.location.state && props.location.state.activeKey) {
      this.state.activeKey = props.location.state.activeKey;
    }
  }

  renderBadge = (count: number, active = false) => {
    return <Badge count={count} style={{
      marginTop: -2,
      marginLeft: 4,
      color: active ? '#1890FF' : '#999',
      backgroundColor: active ? '#E6F7FF' : '#eee'
    }}/>;
  };

  editColumns = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 80,
    valueEnum: manufacturerOption()
  }, {
    title: '产品名称',
    dataIndex: 'product_name',
    ellipsis: true,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    },
    width: 200
  }, {
    title: '产品型号',
    // ellipsis: true,
    dataIndex: 'product_standard',
    width: 200
  }, {
    title: '单位',
    dataIndex: 'packing_unit',
    width: 60,
    ellipsis:true,
  }, {
    title: '剩余发货数量',
    dataIndex: 'send_numbs',
    width: 150
  }, {
    title: '单价(元)',
    valueType: 'money',
    dataIndex: 'standard_price',
    width: 160,
    editable: true,
    render: (_: any, record: any) => {
      if (record.is_gifts == 1) {
        return `0`;
      }

      if (!record.now) {
        if (record.unit_price && Number(record.unit_price) != Number(record.standard_price)) {
          return <>{moneyFormat(record.standard_price)}<span style={{
              textDecoration: 'line-through',
              color: '#d1d1d1',
              marginLeft: 10
            }}>{moneyFormat(record.unit_price)}</span></>;
        }

        return moneyFormat(record.standard_price);
      }

      return moneyFormat(record.standard_price);
    }
  }, {
    title: '现订货数量',
    dataIndex: 'now_numbs',
    editable: true,
    width: 120
  }, {
    title: '金额(元)',
    width: 120,
    valueType: 'money',
    dataIndex: 'actual_amount',
    align: 'left',
    render: (_: any, record: any) => {
      if (record.is_gifts == 1 || record.now_numbs == 0) {
        return `0`;
      }

      return moneyFormat(accMul(Number(record.standard_price) , record.now_numbs));
    }
  }]; 

  buttons = (record:any)=>{
    var array = [<a key='show' onClick={() => this.detail(record)}>详情</a>]
    if(['tab1','tab2','tab3','tab4','tab5'].indexOf(this.state.activeKey)>=0){
      array.push(<a key='history' onClick={() => 
        {
          this.setState({historyVisible:true})
          this.orderHistoryRef.current?.init('id')
        }
      }>改单记录</a>)
    }
    if(record.status!=='4'){
      array.push(<a key="pay" onClick={async() => 
        {
          var param: any = {
            orderId: record.id
          };
          var val = await orderBillInfo(param);
          if (val.errorCode === '200') {
            this.setState({payInfo:val.data})
          }else{
            message.error(val.errorMessage)
          }
        }
      }>付款信息</a>)
    }
    if(record.status!=='5'){
      array.push(<a key='show' onClick={() => this.editOrder(record)}>修改</a>)
    }
    return array
  }
  
  editSendColumns: ProColumns<ProductType>[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 80,
    valueEnum: manufacturerOption()
  }, {
    title: '产品名称',
    dataIndex: 'product_name',
    ellipsis: true,
    width:200,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    },
  }, {
    title: '产品型号',
    // ellipsis: true,
    dataIndex: 'product_standard',
    width: 200
  }, {
    title: '单位',
    dataIndex: 'packing_unit',
    width: 60,
    ellipsis:true,
  }, {
    title: '订货数量',
    dataIndex: 'numbs',
    width: 150
  }, {
    title: '单价(元)',
    dataIndex: 'standard_price',
    width: 160,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `0`;
      }

      if (record.unit_price && Number(record.unit_price) != Number(record.standard_price)) {
        return <>{moneyFormat(record.standard_price)}<span style={{
            textDecoration: 'line-through',
            color: '#d1d1d1',
            marginLeft: 10
          }}>{moneyFormat(record.unit_price)}</span></>;
      }

      return moneyFormat(record.standard_price);
    }
  }, {
    title: '已发货',
    dataIndex: 'send_numbs',
    width: 120
  }, {
    title: '金额(元)',
    dataIndex: 'actual_amount',
    width: 120,
    align: 'left',
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `0`;
      }

      return moneyFormat(accMul(Number(record.standard_price), record.send_numbs));
    }
  }];
  
  giftColumn: ProColumns[] = [{
    title: '客户代码',
    dataIndex: 'dealerCode',
    width: 100,
    editable: false
  }, {
    title: '客户名称',
    dataIndex: 'dealerName',
    editable: false,
    width: 200,
    ellipsis: true
  }, {
    title: '产品名称',
    width: 200,
    ellipsis: true,
    dataIndex: 'productName'
  }, {
    title: '产品型号',
    width: 200,
    ellipsis: true,
    dataIndex: 'productName'
  }, {
    title: '数量',
    hideInSearch: true,
    width: 100,
    dataIndex: 'productNum'
  }, {
    title: '有效期',
    hideInSearch: true,
    valueType: 'date',
    width: 100,
    dataIndex: 'effectData'
  }];
  disColumn: ProColumns[] = [{
    title: '规则编码',
    dataIndex: 'ruleCode',
    width: 150
  }, {
    title: '价格体系',
    dataIndex: 'ruleType',
    valueType: 'select',
    width: 100,
    valueEnum:priceOption()
  }, {
    title: '产品名称',
    dataIndex: 'productName',
    width: 150,
    ellipsis: true
  }, {
    title: '数量≥',
    dataIndex: 'discountNum',
    hideInSearch: true,
    valueType: 'digit',
    width: 120
  }, {
    title: '数量≤',
    dataIndex: 'discountNum2',
    valueType: 'digit',
    hideInSearch: true,
    width: 120
  }, {
    title: '优惠后价格',
    dataIndex: 'discountPrice',
    hideInSearch: true,
    valueType: 'money',
    width: 120
  }, {
    title: '规则说明',
    dataIndex: 'ruleInfo',
    ellipsis: true,
    width: 200,
    hideInSearch: true
  }];
  columns: ProColumns<OrderInfo>[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    valueEnum: manufacturerOption()
  },{
    title: '订单号',
    dataIndex: 'order_number'
  }, {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    valueEnum: {
      1: {
        text: '未提交'
      },
      2: {
        text: '待审核'
      },
      3: {
        text: '未通过'
      },
      4: {
        text: '待付款'
      },
      5: {
        text: '待发货'
      },
      6: {
        text: '待收货'
      },
      7: {
        text: '已完成'
      },
      8: {
        text: '已消退'
      }
    },
    hideInSearch: true
  }, {
    title: '实付金额',
    valueType: 'money',
    dataIndex: 'actual_amount',
    hideInSearch: true
  }, {
    title: '订货日期',
    dataIndex: 'order_time',
    hideInSearch: true
  }, {
    title: '交货日期',
    dataIndex: 'delivery_time',
    hideInSearch: true
  }, {
    title: '订货日期',
    valueType: 'dateRange',
    dataIndex: 'date',
    hideInTable: true
  }, {
    title: '操作',
    key: 'option',
    width: ['tab1','tab2','tab3','tab4','tab5'].indexOf(this.state.activeKey)?240:180,
    valueType: 'option',
    render: (_, record:any) =>  {
      return this.buttons(record)
    }
  }];
  viewPcolumns: ProColumns<ProductType>[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 80,
    valueEnum: manufacturerOption()
  }, {
    title: '产品名称',
    dataIndex: 'product_name',
    ellipsis: true,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    }
  }, {
    title: '产品型号',
    ellipsis: true,
    dataIndex: 'product_standard'
  }, {
    title: '单位',
    dataIndex: 'packing_unit',
    width: 80,
    ellipsis:true,
  }, {
    title: '订货数量',
    dataIndex: 'numbs',
    width: 80
  }, {
    title: '合计',
    dataIndex: 'numbs_count',
    width: 70,
    colSpan: 1,
    align: 'center',
    render: (value: any, record: any) => {
      const obj:any = {
        children: value,
        props: {}
      };
      obj.props.rowSpan = record.name_count;
      return obj;
    }
  }, {
    title: '已发货',
    width: 70,
    dataIndex: 'send_numbs'
  }, {
    title: '已收货',
    width: 70,
    dataIndex: 'received_numbs'
  }, {
    title: '单价(元)',
    dataIndex: 'standard_price',
    align: 'left',
    width: 150,
    render: (_: any, record: any) => {
      if (record.is_gifts === 1) {
        return 0;
      }

      if (record.unit_price && Number(record.unit_price) != Number(record.standard_price)) {
        return <>{moneyFormat(record.standard_price)}<span style={{
            textDecoration: 'line-through',
            color: '#d1d1d1',
            marginLeft: 10
          }}>{moneyFormat(record.unit_price)}</span></>;
      }

      return moneyFormat(record.standard_price);
    }
  }, {
    title: '金额(元)',
    valueType: 'money',
    dataIndex: 'actual_amount',
    align: 'left',
    width: 150
  }];

  async detail(record:any) {
    this.setState({
      spinningFlag: true
    });
    var param: any = {
      orderId: record.id
    };
    var val = await orderDetailDataById(param);

    if (val.errorCode === '200') {
      if (record.status === '1' || record.status === '3') {
        //获取下收货列表
        var address: any = {};
        var addressOptions: any = [];
        val.data.recvlist.forEach((item:any, index:number) => {
          addressOptions.push({
            label: `${item.provinces_label}${item.city_label}${item.area_label}${item.recv_address}`,
            value: index
          });

          if (item.recv_id === record.rec_id) {
            address = { ...item
            };
            address.index = index;
          }
        });

        if (!val.data.order.realAddress) {
          address.realAddress = addressOptions[address.index].label;
        } else {
          address.realAddress = val.data.order.realAddress;
        }

        val.data.list.forEach((item: any) => {
          item.id = item.productId;
          item.rownum = item.sort;

          if (item.unit_price) {
            item.standard_price = item.unit_price;
          }
        });
        address.addressOptions = addressOptions;
        val.data.order_date = record.order_time;
        val.data.delivery_date = record.delivery_time;

        if (record.delivery_time) {
          this.formRef.current.setFieldsValue({
            delivery_date: record.delivery_time
          });
        }

        val.data.dealerId = record.dealerId;
        var saleInfo: any = {};
        var saleOption: any = [];
        val.data.salesList.forEach((item: any) => {
          saleOption.push({
            label: `${item.name}`,
            value: item.id
          });
        });
        saleInfo.saleOption = saleOption;
        saleInfo.salesId = val.data.order.salesId;
        var giftData = await getList4Dealer({
          pageSize: 1000
        }); //使用的返利金额不暂存，每次都是0

        this.setState({
          giftList: giftData.data,
          disList: val.data.discountRulesList,
          fileList: val.data.attList,
          fileId: record.id,
          showCreate: true,
          initData: val.data,
          address: address,
          useMoney: 0,
          editOrder: true,
          currentDay: val.data.order.order_time,
          saleInfo
        });
        this.checkGift(val.data.list, val.data.discountRulesList); //初始化数据
      } else {
        var detailRecv: any = {};
        detailRecv.recvName = record.consignee;
        detailRecv.recvMobile = record.mobile;
        detailRecv.recvAddress = record.delivery_address;
        this.setState({
          fileList: val.data.attList,
          detailFlag: true,
          detailRecv: detailRecv,
          detailProduct: val.data.list,
          detailOrder: record
        });
      }
    } else {
      message.error('获取订单详情失败');
    }

    this.setState({
      spinningFlag: false
    });
  }

  async editOrder(record:any){
    this.setState({
      spinningFlag: true
    });
    var param: any = {
      orderId: record.id
    };
    var val = await orderDetailDataById(param);
    if (val.errorCode === '200') {
      var sentList = [];
      var unsentList = [];
      var sentPrice = 0;

      for (var i = 0; i < val.data.list.length; i++) {
        var item = val.data.list[i];
        item.oldId = item.id;
        item.id = item.productId;
        if (item.is_gifts != 1) {
          sentPrice = accAdd(sentPrice,accMul(item.send_numbs ,Number(item.standard_price)));
        }
        if (item.send_numbs != item.numbs) {
          if (item.send_numbs == 0) {
            item.now_numbs = item.numbs;
            item.send_numbs = item.numbs;
            unsentList.push(item);
          } else {
            sentList.push(item);
            var unsent = { ...item
            };
            unsent.numbs = item.numbs - item.send_numbs;
            unsent.send_numbs = unsent.numbs;
            unsent.now_numbs = unsent.numbs;
            unsent.actual_amount = accMul(Number(unsent.standard_price), unsent.numbs);
            unsentList.push(unsent);
          }
        } else {
          sentList.push(item);
        }
      }

      this.setState({
        editFlag: true,
        initData: val.data,
        dealerCode: record.dealerCode,
        newDataSource: unsentList,
        sentList,
        sentPrice
      });
    } else {
      message.error('获取订单详情失败');
    }

    this.setState({
      spinningFlag: false
    });
  }

  showSentInfo() {}

  formItemLayout = {
    labelCol: {
      span: 6
    },
    wrapperCol: {
      span: 16
    }
  };
  pColumns = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    width: 100,
    valueEnum: manufacturerOption()
  }, {
    title: '产品名称',
    dataIndex: 'product_name',
    ellipsis: true,
    key: 'product_name',
    renderText: (_:string, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    }
  }, {
    title: '产品型号',
    width: 200,
    dataIndex: 'product_standard',
    ellipsis: true,
    key: 'product_standard'
  }, {
    title: '单位',
    dataIndex: 'packing_unit',
    key: 'packing_unit',
    width: 80,
    ellipsis:true,
  }, {
    title: '数量',
    dataIndex: 'numbs',
    editable: true,
    width: 150,
    key: 'numbs'
  }, {
    title: '合计',
    dataIndex: 'numbs_count',
    width: 70,
    colSpan: 1,
    align: 'center',
    render: (value: any, record: any) => {
      const obj:any = {
        children: value,
        props: {}
      };
      obj.props.rowSpan = record.name_count;
      return obj;
    }
  }, {
    title: '单价(元)',
    width: 150,
    align: 'left',
    render: (_: any, record: any) => {
      if (record.is_gifts == 1) {
        return 0;
      }

      if (record.disPrice) {
        return <>{moneyFormat(record.disPrice)}<span style={{
            textDecoration: 'line-through',
            color: '#d1d1d1',
            marginLeft: 10
          }}>{moneyFormat(record.standard_price)}</span></>;
      }

      return moneyFormat(record.standard_price);
    }
  }, {
    title: '金额(元)',
    valueType: 'money',
    width: 150,
    key: 'money',
    align: 'left',
    render: (_: any, record: any) => {
      if (record.is_gifts == 1) {
        return 0;
      }
      if (record.disPrice) {
        return <>{moneyFormat(accMul(record.disPrice , record.numbs))}</>;
      }
      return moneyFormat(accMul(record.standard_price , record.numbs));
    }
  }, {
    title: '操作',
    valueType: 'option',
    width: 150,
    render: (_: any, record: any) => this.state.newDataSource.length >= 1 ? <Popconfirm title='确定删除该产品吗?' onConfirm={() => this.handleDelete(record.id + '_' + record.is_gifts)}>
            <a>删除</a>
          </Popconfirm> : null
  }];
  handleDelete = (id: any) => {
    var newData = this.state.newDataSource.filter((item: any) => item.id + '_' + item.is_gifts !== id); // this.setState({newDataSource:newData});

    this.checkGift(newData, this.state.disList);
  };
  checkGift = (newDS: any[], disList: any) => {
    newDS.sort((a: any, b: any) => {
      if (a.product_name === b.product_name) {
        return a.is_gifts - b.is_gifts;
      }

      return a.product_name < b.product_name ? -1 : 1;
    }); //此处判断下是否有优惠
    //首先统计当前所有产品名称的个数

    var countMap = {};
    var nameMap = {};
    newDS.forEach((item: any) => {
      var key = `${item.product_name}_${item.is_gifts}`;

      if (nameMap[key] !== undefined) {
        nameMap[key].numbs = nameMap[key].numbs + item.numbs;
        nameMap[key].count = nameMap[key].count + 1;
      } else {
        nameMap[key] = {
          numbs: item.numbs,
          count: 1
        };
      }

      if (item.is_gifts === 1) {
        return;
      }

      if (item.rownum < 4) {
        if (countMap[item.product_name]) {
          countMap[item.product_name].nums += item.numbs;
        } else {
          countMap[item.product_name] = {};
          countMap[item.product_name].ruleType = item.rownum;
          countMap[item.product_name].nums = item.numbs;
        }
      }
    });
    console.log(countMap)
    disList.forEach((item: any) => {
      if (countMap[item.productName] && Number(item.ruleType) === countMap[item.productName].ruleType) {
        var nums = countMap[item.productName].nums;

        if (item.discountNum && item.discountNum2) {
          var num1 = Number(item.discountNum);
          var num2 = Number(item.discountNum2);

          if (nums >= num1 && nums <= num2) {
            countMap[item.productName].price = Number(item.discountPrice);
          }
        } else if (item.discountNum) {
          var num1 = Number(item.discountNum);

          if (nums >= num1) {
            countMap[item.productName].price = Number(item.discountPrice);
          }
        }
      }
    });
    var totalMoney = 0;
    var disMoney = 0;
    newDS.forEach((item: any) => {
      var key = `${item.product_name}_${item.is_gifts}`;

      if (nameMap[key] != undefined) {
        item.numbs_count = nameMap[key].numbs;
        item.name_count = nameMap[key].count;
        nameMap[key] = undefined;
      } else {
        item.numbs_count = '';
        item.name_count = 0;
      }
      if (item.is_gifts !== 1) {
        if (countMap[item.product_name] && countMap[item.product_name].price && item.rownum < 4) {
          item.disPrice = countMap[item.product_name].price;
        } else {
          item.disPrice = 0;
        }
        totalMoney = accAdd(totalMoney,accMul(Number(item.standard_price),item.numbs))
        // console.log(totalMoney)
        if (item.disPrice) {
          disMoney = accAdd(disMoney,accMul(accSub(Number(item.standard_price),item.disPrice),item.numbs))
        }
      }
    });
    this.setState({
      newDataSource: newDS,
      disMoney: disMoney,
      totalMoney
    });
  };
  handleSave = (row: any) => {
    const index = this.state.newDataSource.findIndex((item: any) => row.id + '_' + row.is_gifts === item.id + '_' + item.is_gifts);
    const item = this.state.newDataSource[index];
    this.state.newDataSource.splice(index, 1, { ...item,...row});
    let newDS = [...this.state.newDataSource];
    this.checkGift(newDS, this.state.disList);
  };
  saveOrder = async (type: number) => {
    if (this.state.newDataSource.length == 0) {
      message.warning('请先添加产品');
      return false;
    }

    var param: any = {
      order: {},
      product: []
    };
    param.order.type = type;
    param.order.userId = this.userInfo.userId;
    param.order.dealerId = this.userInfo.dealerId;
    param.order.order_date = this.state.currentDay;
    param.order.delivery_date = this.formRef.current.getFieldValue('delivery_date');
    param.order.total = this.state.totalMoney;

    if (type == 0) {
      //返利不暂存
      param.order.use_rebate = 0;
      param.order.discount = this.state.disMoney;
      param.order.actual_amount = accSub(this.state.totalMoney, this.state.disMoney);
    } else {
      param.order.use_rebate = this.state.useMoney;
      param.order.discount = this.state.disMoney;
      param.order.actual_amount = accSub(accSub(this.state.totalMoney,this.state.useMoney), this.state.disMoney);
    }

    var addresIndex = this.formRef.current.getFieldValue('recvAddress');
    param.order.rec_id = this.state.initData.recvlist[addresIndex].recv_id;
    param.order.salesId = this.formRef.current.getFieldValue('salesId');
    param.order.remarks = this.formRef.current.getFieldValue('remarks');
    param.order.realAddress = this.formRef.current.getFieldValue('realAddress');

    if ((!param.order.remarks || param.order.remarks.trim() === '') && type == 1) {
      var flag = false;
      for (var i = 0; i < this.state.newDataSource.length; i++) {
        if (this.state.newDataSource[i].numbs < 0) {
          flag = true;
          break;
        }
      }

      if (flag) {
        message.warning('负数订单请先填写备注');
        return false;
      }
    } //判断下总金额是否小于0，如果小于0，就不能使用返利


    if (this.state.useMoney > 0) {
      var totalMoney = 0;
      this.state.newDataSource.forEach(({
        standard_price,
        numbs,
        is_gifts
      }) => {
        totalMoney =  accAdd(totalMoney, accMul(standard_price,accMul(numbs ,(is_gifts == 1 ? 0 : 1))));
      });

      if (totalMoney < 0) {
        message.warning('负数金额订单不可使用返利金额');
        return false;
      }

      if (this.state.useMoney > this.state.initData.amount) {
        message.warning('返利金额不能大于返利余额');
        return false;
      }
    } else if (this.state.useMoney < 0) {
      message.warning('返利金额不能小于0');
      return false;
    }

    var orderFlag = -1
    var giftFlag = 0
    var boxCheckFlag  = false
    this.state.newDataSource.forEach((item: any) => {
      //此处判断下单位，如果有箱
      if(item.packing_unit.indexOf('把')>=0){
        if(!boxCheckFlag&&item.numbs%10!=0){
          boxCheckFlag=true
        }
        // totalBoxNum=totalBoxNum+item.numbs
      }
      if (orderFlag == -1) {
        orderFlag = item.manufacturer;
      } else {
        if (orderFlag != item.manufacturer) {
          orderFlag = 0;
        }
      }

      if (item.numbs != 0) {
        var p: any = {
          productId: item.id,
          numbs: item.numbs,
          is_gifts: item.is_gifts,
          discount: item.is_gifts == 1 ? 0 : 1
        };

        if (item.is_gifts === 1) {
          giftFlag = 1;
          p.standard_price = 0;
          p.unit_price = 0;
          p.actual_amount = 0;
        } else {
          if (item.disPrice) {
            p.unit_price = Number(item.standard_price);
            p.standard_price = item.disPrice;
            p.actual_amount = accMul(item.disPrice , item.numbs);
          } else {
            p.unit_price = item.standard_price;
            p.standard_price = item.standard_price;
            p.actual_amount = accMul(Number(item.standard_price), item.numbs);
          }
        }

        p.productName = item.product_name;
        p.productStandard = item.product_standard;
        p.sort = item.rownum
        param.product.push(p);
      }
    });
    if (orderFlag == 0) {
      message.warning('下单产品的厂家不一致，请分开下单');
      return false;
    }
    if(boxCheckFlag){
      message.warning('封堵止血系统必须是10的倍数起订！');
      return false;
    }

    if (giftFlag === 1 && type == 0) {
      message.warning('暂存时请先删除赠品');
      return false;
    }

    var val;
    if (this.state.editOrder) {
      param.order.id = this.state.initData.order.id;
      val = await updateOrder(param);
    } else {
      param.order.id = this.state.fileId;
      val = await saveOrderApi(param);
    }

    if (val.errorCode === '200') {
      if (type == 0) {
        message.success('暂存成功');
        this.actionRef.current?.reloadAndRest?.();
      } else {
        message.success('提交成功');
        this.actionRef.current?.reloadAndRest?.();
      }

      this.setState({
        newDataSource: [],
        useMoney: 0,
        fileList: [],
        showCreate: false
      });
      return true;
    } else {
      message.error(val.errorMessage);
      return false;
    }
  };
  disabledDate = (current: any) => {
    return current && current < momentNow().endOf('day');
  };
  handlePreview = async (file: any) => {
    window.open(file.url);
  };

  pratioDesc = ()=>{
    if(this.state.newDataSource.length>0){
      var orderMF = this.state.newDataSource[0].manufacturer+''
      var exitRule = this.state.initData.factoryRules.filter((item:any)=>item.manufacturer==orderMF)
      if(exitRule.length!=0){
        if(exitRule[0].isTogether=='0'){
          return `2.单笔订单使用赠品金额与返利的金额不能超过单笔订单总金额的${100-exitRule[0].pRatio}%`
        }else{
          return `2.单笔订单使用返利的金额不能超过单笔订单总金额的${100-exitRule[0].rebateRatio}%；使用的赠品的金额不能超过单笔订单总金额的${100-exitRule[0].giftRatio}%；`
        }
      }
    }
    return '';
  };

  render() {
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell
      }
    };
    const newColumns = this.editColumns.map(col => {
      if (!col.editable) {
        return col;
      }

      return { ...col,
        onCell: (record: any) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        })
      };
    });
    const columns = this.pColumns.map(col => {
      if (!col.editable) {
        return col;
      }

      return { ...col,
        onCell: (record: any) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        })
      };
    });
    const {
      btnLoading
    } = this.state;
    const uploadProps = {
      name: 'file',
      accept: 'application/pdf',
      action: '/xwyl/attachment/uploadAttach',
      headers: {
        authorization: 'authorization-text'
      },
      beforeUpload: (file: RcFile, FileList: RcFile[]) => {
        var flag = file.type.indexOf('pdf') >= 0;

        if (!flag) {
          message.error('请上传图片格式或pdf格式');
        }

        return flag;
      }
    };
    return <>
    <PageContainer>
    <ProTable<OrderInfo> columns={this.columns} actionRef={this.actionRef} request={(params, sorter, filter) => {
          var other = {
            userId: this.userInfo.userId,
            status: ''
          };

          if (this.state.activeKey === 'tab0') {
            other.status = '1';
          } else if (this.state.activeKey === 'tab1') {
            other.status = '2';
          } else if (this.state.activeKey === 'tab2') {
            other.status = '4';
          } else if (this.state.activeKey === 'tab3') {
            other.status = '5';
          } else if (this.state.activeKey === 'tab4') {
            other.status = '6';
          } else if (this.state.activeKey === 'tab5') {
            other.status = '7';
          } else if (this.state.activeKey === 'tab6') {
            other.status = '3';
          }

          if (params.date) {
            params.beginDate = params.date[0];
            params.endDate = params.date[1];
            params.date = undefined;
          }

          return myOrderData({ ...params,
            filter,
            ...other
          });
        }} search={{
          span: 6,
          collapseRender:false,
          optionRender: ({
            searchText,
            resetText
          }, {
            form
          }) => [<Button key='search' type='primary' onClick={() => {
            form?.submit();
          }}>
            {searchText}
          </Button>, <Button key='rest' onClick={() => {
            form?.resetFields();
            form?.submit();
          }}>
            {resetText}
          </Button>, <Button key='out' onClick={async () => {
            var orderNumber = form?.getFieldValue('order_number');
            var date = form?.getFieldValue('date');
            var params: any = {};

            if (date) {
              params.beginDate = date[0].format('YYYY-MM-DD');
              params.endDate = date[1].format('YYYY-MM-DD');
              params.date = undefined;
            }

            params.order_number = orderNumber;

            if (this.state.activeKey === 'tab0') {
              params.status = 1;
            } else if (this.state.activeKey === 'tab1') {
              params.status = 2;
            } else if (this.state.activeKey === 'tab2') {
              params.status = 4;
            } else if (this.state.activeKey === 'tab3') {
              params.status = 5;
            } else if (this.state.activeKey === 'tab4') {
              params.status = 6;
            } else if (this.state.activeKey === 'tab5') {
              params.status = 7;
            } else if (this.state.activeKey === 'tab6') {
              params.status = 3;
            }

            this.setState({
              spinningFlag: true
            });
            var val = await exportOrder(params);

            if (val.errorCode === '200') {
              exportFile(val.data, '订单.xlsx');
            } else {
              message.error(val.errorMessage);
            }

            this.setState({
              spinningFlag: false
            });
          }}>导出</Button>]
        }} toolbar={{
          menu: {
            type: 'tab',
            activeKey: this.state.activeKey,
            items: [{
              key: 'tab0',
              label: <span>未提交{this.renderBadge(0, this.state.activeKey === 'tab0')}</span>
            }, {
              key: 'tab1',
              label: <span>待审核{this.renderBadge(0, this.state.activeKey === 'tab1')}</span>
            }, {
              key: 'tab2',
              label: <span>待付款{this.renderBadge(0, this.state.activeKey === 'tab2')}</span>
            }, {
              key: 'tab3',
              label: <span>待发货{this.renderBadge(0, this.state.activeKey === 'tab3')}</span>
            }, {
              key: 'tab4',
              label: <span>待收货{this.renderBadge(0, this.state.activeKey === 'tab4')}</span>
            }, {
              key: 'tab5',
              label: <span>已完成{this.renderBadge(0, this.state.activeKey === 'tab5')}</span>
            }, {
              key: 'tab6',
              label: <span>未通过{this.renderBadge(0, this.state.activeKey === 'tab6')}</span>
            }],
            onChange: key => {
              this.setState({
                activeKey: (key as string)
              });
              this.actionRef.current?.reloadAndRest?.();
            }
          },
          settings: []
        }} toolBarRender={() => [<Button type='primary' hidden={sessionStorage.getItem('isOrder')==='0'} key='primary' onClick={async () => {
          
          var val: any = await request('/xwyl/dealer/dealerRequiredMsg', {
            params: {dealerId:sessionStorage.getItem('dealerId')}
          });
          if (val.success&&val.data.requiredMsg.length>0) {
            Modal.warning({
              title: '提示',
              content: (
                <div>
                  <p style={{color:'#f10000'}}>未填写完整将不能下单，请尽快填写更新!</p>
                  {val.data.requiredMsg.map((item:any)=>{
                    return <p>{item}</p>
                  })}
                </div>
              ),
              onOk() {
                window.location.href = '/jf/#/baseinfo';
              },
            });
            return
          }
          this.setState({
            spinningFlag: true
          });
          var user = {
            'userId': this.userInfo.userId
          };
          val = await toPlaceOrderNew(user);

          if (val.errorCode === '200') {
            var address: any = {};
            var addressOptions: any = [];
            var flag = false;
            val.data.recvlist.forEach((item: any, index: number) => {
              addressOptions.push({
                label: `${item.provinces_label}${item.city_label}${item.area_label}${item.recv_address}`,
                value: index
              });

              if (item.recv_default == 1) {
                address = { ...item
                };
                address.index = index;
                flag = true;
              }
            });

            if (!flag) {
              this.setState({
                spinningFlag: false
              });
              message.error('暂无默认收货地址，请先添加默认收货地址');
              return;
            }

            address.addressOptions = addressOptions;
            address.realAddress = addressOptions[address.index].label;
            var saleInfo: any = {};
            var saleOption: any = [];
            val.data.salesList.forEach((item: any) => {
              saleOption.push({
                label: `${item.name}`,
                value: item.id
              });
            });
            saleInfo.saleOption = saleOption;

            if (saleOption.length == 1) {
              saleInfo.salesId = saleOption[0].value;
            }

            var giftData = await getList4Dealer({
              pageSize: 1000
            });
            this.setState({
              giftList: giftData.data,
              disList: val.data.discountRulesList,
              fileId: val.data.orderId,
              initData: val.data,
              showCreate: true,
              address: address,
              editOrder: false,
              currentDay: getCurrentDate(),
              saleInfo,
              giftFlag: false
            });
          } else {
            message.error('初始化订单失败');
          }

          this.setState({
            spinningFlag: false
          });
        }}>
          <PlusOutlined />下单
        </Button>]} rowKey='id' pagination={{
          pageSizeOptions: ['20', '100', '500']
        }} dateFormatter='string'  />
    <Drawer width={1100} title={'详情'} visible={this.state.detailFlag} onClose={() => {
          this.setState({
            detailFlag: false,
            fileList: []
          });
        }}>
        <Row style={{
            marginLeft: '22px'
          }}>
          <Col span={4}><UpDownLabel title='订单号' texts={[this.state.detailOrder?.order_number]}/></Col>
          <Col span={4}><UpDownLabel title='销售' texts={[this.state.detailOrder.salesName]} /></Col>
          <Col span={8}><UpDownLabel title='收货地址' texts={[this.state.detailRecv.recvAddress]}/></Col>
          <Col span={4}><UpDownLabel title='收货人' texts={[this.state.detailRecv.recvName]}/></Col>
          <Col span={4}><UpDownLabel title='收货电话' texts={[this.state.detailRecv.recvMobile]}/></Col>
        </Row>
        <Row style={{
            marginLeft: '22px'
          }} >
          <UpDownLabel title='出库单地址' texts={[this.state.detailOrder.realAddress]}/>
        </Row>
        <ProTable<ProductType> headerTitle='订单产品' toolbar={{
            settings: []
          }} columns={this.viewPcolumns} dataSource={this.state.detailProduct} rowKey='id' pagination={false} search={false} summary={pageData => {
            return <>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={5}>总金额:</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='center'>
                          {this.state.detailProduct.reduce(function (total, currentValue, currentIndex, arr) {
                    return currentValue['numbs'] ? total + currentValue['numbs'] : total;
                  }, 0)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={3} align='left'>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                      ￥{moneyFormat(this.state.detailOrder.total)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={9}>优惠金额:</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left'>
                    ￥{moneyFormat2(this.state.detailOrder.discount)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={9}>返利金额:</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left'>
                    ￥{moneyFormat2(this.state.detailOrder.use_rebate)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={9}>
                    实付金额：
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left'>
                    ￥{moneyFormat(this.state.detailOrder.actual_amount)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                </>;
          }}>
        </ProTable>
        <Row style={{
            margin: '22px'
          }}>
          <Upload fileList={this.state.fileList} onPreview={this.handlePreview} showUploadList={{
              showRemoveIcon: false
            }}>
          </Upload>
        </Row>
        <Row style={{
            margin: '22px'
          }}>
          <Col span={24}><UpDownLabel title='备注' texts={[this.state.detailOrder.remarks]}/></Col>
          {this.state.detailOrder.opinion ? <Col span={24}><UpDownLabel title='审核结果' texts={[this.state.detailOrder.opinion]} /></Col> : <a key='o'></a>}
        </Row>
      </Drawer>
      <DrawerForm title='下订单' width={1250} drawerProps={{
          destroyOnClose: true
        }} formRef={this.formRef} onVisibleChange={val => {
          this.setState({
            showCreate: val
          });

          if (!val) {
            this.setState({
              newDataSource: [],
              useMoney: 0,
              fileList: []
            });
          }
        }} visible={this.state.showCreate} onFinish={async (values: any) => {
          var flag = false;
          var giftMoney = 0;
          var priceMap = {};
          for (var i = 0; i < this.state.newDataSource.length; i++) {
            if (this.state.newDataSource[i].is_gifts !== 1) {
              var key = this.state.newDataSource[i].product_name;
              if (this.state.newDataSource[i].disPrice) {
                priceMap[key] = this.state.newDataSource[i].disPrice;
              }
            }
          }
          for (var i = 0; i < this.state.newDataSource.length; i++) {
            if (this.state.newDataSource[i].is_gifts === 1 && this.state.newDataSource[i].numbs <= 0) {
              flag = true;
              break;
            }

            if (this.state.newDataSource[i].is_gifts === 1) {
              if (this.state.newDataSource[i].rownum < 4 && priceMap[this.state.newDataSource[i].product_name]) {
                giftMoney = accAdd(giftMoney ,accMul(Number(priceMap[this.state.newDataSource[i].product_name]) , Number(this.state.newDataSource[i].numbs)));
              } else {
                giftMoney = accAdd(giftMoney ,accMul(Number(this.state.newDataSource[i].standard_price) , Number(this.state.newDataSource[i].numbs)));
              }
            }
          }
          if (flag) {
            message.warning('赠品数量需大于0');
            return false;
          }


          //计算金额比例
          var orderMF = this.state.newDataSource[0].manufacturer+''
          var exitRule = this.state.initData.factoryRules.filter((item:any)=>item.manufacturer==orderMF)
          if(exitRule.length==0){
            message.warning('暂未设置比例规则，请联系管理员！');
            return false
          }
          if(exitRule[0].isTogether=='0'){
              //合并计算
              var pratio = Number(exitRule[0].pRatio)
              if (giftMoney + this.state.totalMoney - this.state.disMoney > (this.state.totalMoney - this.state.disMoney - this.state.useMoney) * (100/pratio)) {
                message.warning(`实付金额不能超过订单总金额的${100-pratio}%`);
                return false
              }
          }else{
            if(giftMoney>0&&this.state.useMoney!=0){
               message.warning('赠品和返利不能同时使用');
               return false
            }
            //分开计算
            var pratio = Number(exitRule[0].giftRatio)
            if (giftMoney>0&&giftMoney + this.state.totalMoney - this.state.disMoney > (this.state.totalMoney - this.state.disMoney - this.state.useMoney) * (100/pratio)) {
              message.warning(`赠品的金额不能超过订单总金额的${100-pratio}%`);
              return false
            }
            pratio = Number(exitRule[0].rebateRatio)
            if (this.state.useMoney!=0&&giftMoney + this.state.totalMoney - this.state.disMoney > (this.state.totalMoney - this.state.disMoney - this.state.useMoney) * (100/pratio)) {
              message.warning(`返利的金额不能超过订单总金额的${100-pratio}%`);
              return false
            }
          }
          if (this.state.fileList.length == 0) {
            message.warning('请上传订货合同');
            return false;
          }
          return this.saveOrder(1);
        }} submitter={{
          searchConfig: {
            submitText: '提交',
            resetText: '取消'
          },
          render: (props, defaultDoms) => {
            return [...defaultDoms, <Button danger loading={btnLoading} key='ok' onClick={() => {
              this.setState({
                btnLoading: true
              });
              this.saveOrder(0);
              this.setState({
                btnLoading: false
              });
            }}>
                  暂存
                </Button>];
          }
        }} layout='horizontal' labelAlign='left' {...this.formItemLayout}>
        <Row gutter={5}>
             <Col span={8}>
              <span>订货日期:</span>
              <div style={{
                display: 'inline-block',
                marginLeft: '30px'
              }}>{this.state.currentDay}</div>
             </Col>
             <Col span={8}>
              <ProFormDatePicker fieldProps={{
                disabledDate: this.disabledDate
              }} name='delivery_date' label='交货日期' placeholder='请选择交货日期' rules={[{
                required: true
              }]}/>
             </Col>
             <Col span={8}>
              <ProFormSelect name='salesId' label='销售' initialValue={this.state.saleInfo?.salesId} options={this.state.saleInfo?.saleOption} rules={[{
                required: true
              }]}/>
             </Col>
        </Row>
        <Row gutter={5}>
            <Col span={24}>
            <span>收货地址:</span>
            <div style={{
                display: 'inline-block',
                marginLeft: '30px',
                width: 700
              }}>
            <ProFormSelect fieldProps={{
                  onChange: (e: number, v: any) => {
                    var address = this.state.initData.recvlist[e];
                    this.formRef.current.setFieldsValue({
                      recvMail: address.recv_postcode
                    });
                    this.formRef.current.setFieldsValue({
                      recvName: address.recv_consignee
                    });
                    this.formRef.current.setFieldsValue({
                      recvPhone: address.recv_phone
                    });
                    this.formRef.current.setFieldsValue({
                      recvAddress: e
                    });
                    this.formRef.current.setFieldsValue({
                      realAddress: v.label
                    });
                    var newAddress: any = { ...this.state.address
                    };
                    newAddress.recv_postcode = address.recv_postcode;
                    newAddress.recv_consignee = address.recv_consignee;
                    newAddress.recv_phone = address.recv_phone;
                    this.setState({
                      address: newAddress
                    });
                  }
                }} name='recvAddress' style={{
                  width: '700px'
                }} width='xl' initialValue={this.state.address?.index} allowClear={false} rules={[{
                  required: true
                }]} options={this.state.address?.addressOptions}/></div>
            <Button key='addAddress' type='primary' onClick={() => {
                history.push({
                  pathname: '/baseinfo',
                  state: {
                    activeKey: '4'
                  }
                });
              }}>新增地址</Button>
            </Col>
        </Row>
        <div style={{
            marginTop: 10,
            marginBottom: 20
          }}>
          <Row gutter={5}>
              <Col span={8}>
                <span>邮编:</span>
                <div style={{
                  display: 'inline-block',
                  marginLeft: '30px'
                }}>{this.state.address?.recv_postcode}</div>
                </Col>
              <Col span={8}>
                <span>收货人:</span>
                <div style={{
                  display: 'inline-block',
                  marginLeft: '30px'
                }}>{this.state.address?.recv_consignee}</div>
              </Col>
              <Col span={8}>
              <span>电话:</span>
                <div style={{
                  display: 'inline-block',
                  marginLeft: '30px'
                }}>{this.state.address?.recv_phone}</div>
              </Col>

            </Row>
          </div>
          <div style={{
            marginTop: 10,
            marginBottom: 20
          }}>
            <span>出库单地址:</span>
            <div style={{
              display: 'inline-block',
              width: 832,
              marginLeft: '30px'
            }}><ProFormText name='realAddress' initialValue={this.state.address?.realAddress} /></div>
          </div>
          <ProTable<ProductType> rowKey={(record: ProductType) => record.id + '_' + record.is_gifts} components={components} pagination={false} size='small' dataSource={this.state.newDataSource} search={false} toolBarRender={false} columns={columns} summary={pageData => {
            return <>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={2}>
                      <Button type='primary' icon={<PlusOutlined/>} onClick={() => {
                    this.setState({
                      gift: 0,
                      proModalVisible: true
                    });
                  }} >
                        添加订购产品
                      </Button>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={3} align='right'>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='center'>
                      <span>{this.state.newDataSource.reduce(function (total, currentValue, currentIndex, arr) {
                      return currentValue['numbs'] ? total + currentValue['numbs'] : total;
                    }, 0)}</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left'>
                    <div hidden={this.state.giftList.length === 0}>
                      <span style={{
                      lineHeight: '30px'
                    }}>有可选赠品：</span>
                      <span onClick={() => {
                      this.setState({
                        showGift: true
                      });
                    }}><QuestionCircleOutlined/></span>
                    </div>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left'>
                      <Button type='primary' hidden={this.state.giftList.length === 0} onClick={() => {
                    this.setState({
                      gift: 1,
                      proModalVisible: true
                    });
                  }}>
                        选择赠品
                      </Button>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1}>
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={2}>
                      <span style={{
                    lineHeight: '30px'
                  }}>可使用返利余额：￥{moneyFormat(this.state.initData.amount)}</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={4}><span style={{
                    color: '#f10000'
                  }}>【重要提示：有返利余额的，请优先使用返利余额，以免过期不能使用】</span></Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left'>
                      <span style={{
                    lineHeight: '30px'
                  }}>使用返利金额：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align='left'>
                    <InputNumber onBlur={node => {
                    this.setState({
                      useMoney: Number(node.target.value)
                    });
                  }} min={0} max={this.state.initData.amount} placeholder='请输入' precision={0} value={this.state.useMoney}/>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}>
                    元
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={9}>
                      <div style={{position:'relative'}}>
                        <div style={this.state.more?{height:'auto'}:{height:24,overflow:'hidden'}}>
                          <span style={{
                        fontSize: 12,
                        color: '#f10000'
                      }} >【返利使用规则】<br/>1.返利金额不计入季度达成，季度达成金额统计的是下订单实际支付金额。<br/>{this.pratioDesc()}<br/>
                          【运输费】<br/>1.单笔订单总额超过人民币伍万元（包含伍万元），运输费用由医疗承担，没超过人民币伍万元的由客户承担。<br/>2.如无特殊情况，一律平邮寄出。
                          </span>
                        </div>
                        {this.state.more?<UpOutlined onClick={()=>this.setState({more:!this.state.more})} style={{position:'absolute',right:20,top:10}}/>:
                          <DownOutlined onClick={()=>this.setState({more:!this.state.more})} style={{position:'absolute',right:20,top:10}}/>
                        }
                      </div>
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={7}>总金额：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                      ￥{moneyFormat(this.state.totalMoney)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                  <Table.Summary.Row >
                    <Table.Summary.Cell index={1} colSpan={7}>优惠金额：<span onClick={() => {
                    this.setState({
                      showDiscount: true
                    });
                  }}><QuestionCircleOutlined/></span></Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                    ￥{moneyFormat2(this.state.disMoney)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={7}>返利金额：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                    ￥{moneyFormat2(this.state.useMoney)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={7}>
                      <span style={{
                    lineHeight: '30px'
                  }}>实付金额：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                    ￥{moneyFormat(this.state.totalMoney - this.state.useMoney - this.state.disMoney)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                </>;
          }}/>
      
        <Row style={{
            marginTop: '22px'
          }}>
           
            <Col span={24}>
             <Button type='primary' style={{marginRight:20}} key="contract_p" onClick={() => {
                              window.open('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.hngp.gov.cn%2Fwebfile%2Fpdsjx%2Frootfiles%2F2020%2F07%2F20%2F8eecc11b71df48189cc716af72dce15e.jpg&refer=http%3A%2F%2Fwww.hngp.gov.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1665041963&t=e0e36c2252198260ebc3630783e29981')
                          }} >订货合同预览</Button>
              <Button style={{marginRight:20}} type='primary' key="contract_d" onClick={() => {
              exportFile('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.hngp.gov.cn%2Fwebfile%2Fpdsjx%2Frootfiles%2F2020%2F07%2F20%2F8eecc11b71df48189cc716af72dce15e.jpg&refer=http%3A%2F%2Fwww.hngp.gov.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1665041963&t=e0e36c2252198260ebc3630783e29981','合同.png')
            }} >订货合同下载</Button>
             <Upload {...uploadProps} maxCount={1} fileList={this.state.fileList} showUploadList={{
                showRemoveIcon: false
              }} onPreview={this.handlePreview} onChange={(info: any) => {
                if (info.file.status === 'done') {
                  if (info.file.response.errorCode === '200') {
                    // var fileList:any[] = this.state.fileList;
                    var fileList: any[] = [];
                    message.success(`${info.file.name}上传成功`);
                    var data = info.file.response.data;
                    data.uid = data.attId;
                    data.name = info.file.name;
                    data.url = data.location;
                    data.status = 'done';
                    fileList.push(data);
                    this.setState({
                      fileList: [...fileList]
                    });
                  } else {
                    message.error(`${info.file.name} 上传失败.`);
                  }
                } else if (info.file.status === 'error') {
                  message.error(`${info.file.name} 上传失败.`);
                }
              }} data={{
                'shipId': this.state.fileId,
                'userId': sessionStorage.getItem('userId'),
                'clear': 1
              }} headers={{
                'authorization': `${sessionStorage.getItem('token')}`
              }}>
                <Button type='primary'><span style={{
                    color: '#ff0000'
                  }}>*</span>订货合同上传</Button>
              </Upload>
          </Col>
        </Row>
        <Row style={{
            marginTop: '22px'
          }} hidden={!this.state.initData?.order?.opinion}>
          未通过原因：{this.state.initData?.order?.opinion}
        </Row>
        <Row style={{
            marginTop: '22px'
          }}>
          <Col span={24}>
              <ProFormTextArea name='remarks' placeholder={'请填写'} label='备注：' initialValue={this.state.initData?.order?.remarks} fieldProps={{
                showCount: true,
                maxLength: 500
              }}/>
          </Col>
        </Row>
         </DrawerForm>
         <ProductChooseForm self={true} onCancel={() => {
          this.setState({
            proModalVisible: false
          });
        }} onSubmit={async (value: ProductType[]) => {
          // value.forEach((item:any)=>{
          //   if(item.is_gifts===1){
          //     // item.max = 10
          //   }
          // })
          var dataSource = [...this.state.newDataSource, ...value];
          this.setState({
            proModalVisible: false
          }); // this.setState({newDataSource:dataSource});
          // console.log(dataSource,this.state.disList)

          this.checkGift(dataSource, this.state.disList);
        }} modalVisible={this.state.proModalVisible} values={this.state.newDataSource} gift={this.state.gift} admin={false}/>
          <Modal visible={this.state.showDiscount} footer={null} width={1000} onCancel={() => this.setState({
          showDiscount: false
        })}>
             <ProTable headerTitle={<>优惠规则<span style={{
              color: '#f10000',
              marginLeft: 20
            }}>特殊价格商品不参与优惠</span><span></span></>} pagination={{
            pageSizeOptions: ['20', '100', '500']
          }} dataSource={this.state.disList} columns={this.disColumn} rowKey='id' search={false} toolBarRender={false} toolbar={{
            settings: []
          }}/>
         </Modal>
         <Modal visible={this.state.showGift} footer={null} width={1000} onCancel={() => this.setState({
          showGift: false
        })}>
             <ProTable headerTitle='赠品列表' pagination={{
            pageSizeOptions: ['20', '100', '500']
          }} dataSource={this.state.giftList} columns={this.giftColumn} rowKey='id' search={false} toolBarRender={false} toolbar={{
            settings: []
          }}/>
         </Modal>
  
         <Modal visible={this.state.payInfo?.billName.length>0} footer={null} width={800} onCancel={() => this.setState({payInfo: {billName:''}})}>
          
          <Row >
          <Col span={12}><UpDownLabel title='公司名称' texts={[this.state.payInfo?.billName]}/></Col>
          <Col span={12}><UpDownLabel title='纳税人识别号' texts={[this.state.payInfo?.taxpayerNumber]}/></Col>
        </Row>
        <Row>
          <Col span={12}><UpDownLabel title='开户银行' texts={[this.state.payInfo?.billBank]}/></Col>
          <Col span={12}><UpDownLabel title='银行账号' texts={[this.state.payInfo?.account]}/></Col>
        </Row>
         </Modal>

         <DrawerForm title={'订单修改'} width={1200} visible={this.state.editFlag} drawerProps={{
        destroyOnClose: true,
        forceRender: true
      }} submitter={{
        searchConfig: {
          submitText: '保存',
          resetText: '取消'
        }
      }} onFinish={async values => {
        var param: any = {
          product: [],
          remarks: values.remarks
        };
        var totalMoney = 0;
        this.state.sentList.forEach((item: any) => {
          var sendItem: any = {
            orderId: this.state.initData.order?.id,
            id: item.oldId,
            send_numbs: item.send_numbs,
            productId: item.id,
            numbs: item.send_numbs,
            sort:item.sort,
            is_gifts: item.is_gifts
          };

          if (item.is_gifts === 1) {
            sendItem.unit_price = 0;
            sendItem.standard_price = 0;
            sendItem.actual_amount = 0;
          } else {
            if (item.unit_price) {
              sendItem.unit_price = item.unit_price;
              sendItem.standard_price = item.standard_price;
              sendItem.actual_amount = accMul(item.send_numbs , Number(item.standard_price));
            } else {
              sendItem.unit_price = item.standard_price;
              sendItem.standard_price = item.standard_price;
              sendItem.actual_amount = accMul(item.send_numbs , Number(item.standard_price));
            }
          }
          
          param.product.push(sendItem);
        });
        this.state.newDataSource.forEach((item: any) => {
          if (item.now_numbs > 0) {
            var newItem: any = {
              orderId: this.state.initData.order?.id,
              id: item.oldId,
              send_numbs: 0,
              productId: item.id,
              numbs: item.now_numbs,
              sort:item.sort,
              is_gifts: item.is_gifts
            };

            if (item.is_gifts === 1) {
              newItem.unit_price = 0;
              newItem.standard_price = 0;
              newItem.actual_amount = 0;
            } else {
              if (item.unit_price) {
                newItem.unit_price = item.unit_price;
                newItem.standard_price = item.standard_price;
              } else {
                newItem.standard_price = item.standard_price;
                newItem.unit_price = newItem.standard_price;
              }

              newItem.actual_amount = accMul(Number(newItem.standard_price) , Number(item.now_numbs));
              totalMoney = accAdd(totalMoney , Number(newItem.actual_amount));
            }

            param.product.push(newItem);
          }
        });
        var discount = this.state.initData?.order.discount;

        if (!discount) {
          discount = 0;
        }

        console.log(param, totalMoney, this.state.sentPrice);

        if (totalMoney != Number(this.state.initData?.order.actual_amount) - Number(this.state.sentPrice)+ Number(this.state.initData?.order.use_rebate)) {
          message.error('商品金额检验失败，请重新填写');
          return false;
        }

        // var val = await modifyOrder(param);

        // if (val.errorCode === '200') {
        //   this.actionRef.current?.reloadAndRest?.();
        //   return true;
        // } else {
        //   message.error(val.errorMessage);
        //   return false;
        // }
        return false;
      }} onVisibleChange={val => {
        this.setState({
          editFlag: val
        });

        if (!val) {
          this.setState({
            initData: {}
          });
        }
      }}>
            <Row style={{
          marginLeft: '22px'
        }}>
              <Col span={5}><UpDownLabel title='订单号' texts={[this.state.initData?.order?.order_number]} /></Col>
              <Col span={5}><UpDownLabel title='客户代码' texts={[this.state.dealerCode]} /></Col>
              <Col span={5}><UpDownLabel title='客户名称' texts={[this.state.initData?.order?.dealerName]} /></Col>
              <Col span={5}><UpDownLabel title='订货日期' texts={[this.state.initData?.order?.order_time]} /></Col>
              <Col span={4}><UpDownLabel title='交货日期'  texts={[this.state.initData?.order?.delivery_time]}  /></Col>
            </Row>
            <Row style={{
          marginLeft: '22px'
        }}>
              <Col span={5}><UpDownLabel title='付款方式' texts={[this.state.initData?.order?.payment_method]}  /></Col>
              <Col span={5}><UpDownLabel title='运费方式' texts={[this.state.initData?.order?.postPayMethod]} /></Col>
              <Col span={5}><UpDownLabel title='销售' texts={[this.state.initData?.order?.salesName]} /></Col>
              <Col span={5}><UpDownLabel title='收货人' texts={[this.state.initData?.order?.consignee]}  /></Col>
              <Col span={4}><UpDownLabel title='收货电话' texts={[this.state.initData?.order?.mobile]} /></Col>
            </Row>
            <Row style={{
          marginLeft: '22px'
        }}>
              <Col span={24}><UpDownLabel title='收货地址' texts={[this.state.initData?.order?.provinces_label + this.state.initData?.order?.city_label + this.state.initData?.order?.area_label + ' - ' + this.state.initData?.order?.delivery_address]}/></Col>
            </Row>
            <ProTable<ProductType> headerTitle='已发货产品' size='small' toolbar={{
          settings: []
        }} columns={this.editSendColumns} dataSource={this.state.newDataSource} rowKey={(record: ProductType) => record.id + '_' + record.is_gifts} pagination={false} search={false}>
            </ProTable>
            <ProTable<ProductType> headerTitle='订单产品' size='small' toolbar={{
          settings: []
        }} components={components} columns={newColumns} dataSource={this.state.newDataSource} rowKey={(record: ProductType) => record.id + '_' + record.is_gifts} pagination={false} search={false} summary={pageData => {
          return <>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={1} colSpan={2}>
                          <Button type='primary' icon={<PlusOutlined/>} onClick={() => {
                  this.setState({
                    gift: 0,
                    proModalVisible: true
                  });
                }}>
                            添加订购产品
                          </Button>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={5} align='right'>
                         
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                          <Button type='primary' onClick={() => {
                  this.setState({
                    gift: 1,
                    proModalVisible: true
                  });
                }}>
                            选择赠品
                          </Button>
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={1} colSpan={2}>
                          <span style={{
                        lineHeight: '30px'
                      }}>可使用返利余额：￥{moneyFormat(this.state.initData.amount)}</span>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={4}><span style={{
                        color: '#f10000'
                      }}>【重要提示：有返利余额的，请优先使用返利余额，以免过期不能使用】</span></Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                          <span style={{
                        lineHeight: '30px'
                      }}>使用返利金额：</span>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                        <InputNumber onBlur={node => {
                        this.setState({
                          useMoney: Number(node.target.value)
                        });
                      }} min={0} max={this.state.initData.amount} placeholder='请输入' precision={0} value={this.state.useMoney}/>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={1}>
                        元
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={1} colSpan={7}>待发货金额:</Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                        ￥{moneyFormat((this.state.initData?.order.actual_amount - this.state.sentPrice) + Number(this.state.initData?.order.use_rebate) )}
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={1} colSpan={7}>总金额:</Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                        ￥{moneyFormat(this.state.initData?.order.total)}
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={1} colSpan={7}>优惠金额:</Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                        ￥{moneyFormat2(this.state.initData?.order?.discount)}
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={1} colSpan={7}>返利金额:</Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                        ￥{moneyFormat2(this.state.initData?.order.use_rebate)}
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={1} colSpan={7}>实付金额:</Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                        ￥{moneyFormat(this.state.initData?.order.actual_amount)}
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                    </>;
        }}>
            </ProTable>

            <Row style={{
          margin: '22px'
        }} >
              <Col span={24}>
                <ProFormTextArea name='remarks' initialValue={this.state.initData?.order?.remarks} placeholder={'请填写备注'} label='备注：' fieldProps={{
              showCount: true,
              maxLength: 500
            }}/>
              </Col> 
            </Row>

            <Row style={{
          margin: '22px 0'
        }} >
          <Upload {...uploadProps} maxCount={1} fileList={this.state.fileList} showUploadList={{
                        showRemoveIcon: false
                      }} onPreview={this.handlePreview} onChange={(info: any) => {
                        if (info.file.status === 'done') {
                          if (info.file.response.errorCode === '200') {
                            var fileList: any[] = [];
                            message.success(`${info.file.name}上传成功`);
                            var data = info.file.response.data;
                            data.uid = data.attId;
                            data.name = info.file.name;
                            data.url = data.location;
                            data.status = 'done';
                            fileList.push(data);
                            this.setState({
                              fileList: [...fileList]
                            });
                          } else {
                            message.error(`${info.file.name} 上传失败.`);
                          }
                        } else if (info.file.status === 'error') {
                          message.error(`${info.file.name} 上传失败.`);
                        }
                      }} data={{
                        'shipId': this.state.fileId,
                        'userId': sessionStorage.getItem('userId'),
                        'clear': 1
                      }} headers={{
                        'authorization': `${sessionStorage.getItem('token')}`
                      }}>
                    <Button icon={<UploadOutlined/>}><span style={{
                            color: '#ff0000'
                          }}>*</span>上传订货合同<span style={{
                            color: '#ff0000'
                          }}>(PDF格式文件)</span></Button><span style={{color: '#ff0000'}}>订货合同模板在：【信息发布-通知公告-下单说明】里面下载。</span>
                  </Upload>
            </Row>
          </DrawerForm>
          <Modal  title=""
        width={'90%'}
        footer={false}
        destroyOnClose={true}
        visible={this.state.historyVisible}
        onCancel={()=>{
            this.setState({historyVisible:false})
        }}>
          <OrderHistory  ref={this.orderHistoryRef}></OrderHistory>
       </Modal>
         <Spin spinning={this.state.spinningFlag} style={{
          transform: 'translate(-50%,-50%)',
          left: '50%',
          top: '50%',
          position: 'absolute'
        }}/>
    </PageContainer>
    </>;
  }

}

export default Order;